import {useEffect, useState} from "react";
import { RespDataType, getMenuTree } from '../api';


interface FormatMenuData{
    pidToChildIdList: {[index: number]: number[]},
    childIdToPid: {[index: number]: number},
}


export const useList = () => {
    const [ loading, setLoading ] = useState(true);
    const [ initData, setInitData ] = useState<{
        menuTree: RespDataType.MenuTree,
        formatMenuData: FormatMenuData,
    }>({
        menuTree: [],
        formatMenuData:{
            pidToChildIdList: {},
            childIdToPid:{}
        }
    });


    useEffect(() => {
        setLoading(true);
        getMenuTree().then((resp) => {
            const menuTree = resp.data || [];
            setInitData({
                menuTree,
                formatMenuData: doFormatMenuData(menuTree),
            })
            setLoading(false);
        })
    }, []);

    return { loading, initData};
}

const doFormatMenuData = (menuTree: RespDataType.MenuTree, pidToChildIdList:{[index: number]: number[]} = {}, childIdToPid:{[index: number]: number} = {}) =>{
    menuTree.forEach((item) => {
        if(item.children && item.children.length > 0){
            pidToChildIdList[item.id] = item.children.map((childItem) => childItem.id);
            item.children.forEach((childItem) => {
                childIdToPid[childItem.id] = item.id;
            });
            doFormatMenuData(item.children, pidToChildIdList, childIdToPid)
        }
    })

    return {pidToChildIdList, childIdToPid};
}

